package com.nbstar.film.spider.thread;

import com.nbstar.film.spider.pojo.FilmInfo;
import com.nbstar.film.spider.spider.*;

import java.util.concurrent.CountDownLatch;

public class SpiderRequestThread extends Thread {

    public enum RequestType {
        DOUBAN,
        IMDB,
        MAOYAN,
        TVMAO,
        YOUKU,
        AIQIYI,
        TENGXUN
    }

    private BaseSpider spider = null;
    private String     filmName = "";
    private RequestType type ;

    private CountDownLatch latch;

    private FilmInfo result = null;

    public FilmInfo getResult() {
        return result;
    }

    public SpiderRequestThread(CountDownLatch await, RequestType type, String filname) throws Exception {
        switch (type) {
            case IMDB:
                spider = new ImdbSpider();
                break;
            case DOUBAN:
                spider = new DoubanFilmSpider();
                break;
            case MAOYAN:
                spider = new MaoYanSpider();
                break;
            case TVMAO:
                spider = new TVCatSpider(TVCatSpider.MediaType.TV);
                break;
            default:
                throw new Exception("Unsupport spider type!");
        }

        spider.setRetry(0);

        this.type = type;

        this.filmName = filname;
        this.latch = await;
    }

    @Override
    public void run() {
        try {
            //FilmInfo filmInfo = spider.runProxy(filmName);
            FilmInfo filmInfo = spider.runProxy(filmName);;
//            //if (ProxyThread.ipPool.size() > 0) {
//                filmInfo = spider.runProxy(filmName);
//            } else {
//                filmInfo = spider.run(filmName);
//            }
            filmInfo.setCname(filmName);

            this.result = filmInfo;

            System.out.println(type + ":" + filmInfo);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            latch.countDown();
        }


    }
}
